import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'screens/home_screen.dart';
import 'providers/member_provider.dart';
import 'providers/auth_provider.dart';
import 'models/member.dart';
import 'providers/task_provider.dart';
import 'providers/member_filter_provider.dart';
import 'services/notification_service.dart';
import 'providers/theme_provider.dart';
import 'package:window_manager/window_manager.dart';
import '../widgets/custom_window_frame.dart';
import 'services/database_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 添加错误捕获
  FlutterError.onError = (FlutterErrorDetails details) {
    debugPrint('Flutter error: ${details.exception}');
    FlutterError.presentError(details);
  };

  // 声明在 try 块外部
  final themeProvider = ThemeProvider();

  try {
    // 初始化数据库
    sqfliteFfiInit();
    databaseFactory = databaseFactoryFfi;

    // 预加载主题设置
    await themeProvider.loadThemePreferences();

    // 确保数据库可以正常打开
    final db = DatabaseService();
    await db.database;

    // 初始化窗口管理器
    await windowManager.ensureInitialized();
    await windowManager.waitUntilReadyToShow();

    // 配置窗口
    await windowManager.setTitleBarStyle(TitleBarStyle.hidden);
    await windowManager.setMinimumSize(const Size(800, 600));
    await windowManager.setSize(const Size(1200, 800));
    await windowManager.center();

    // 初始化通知服务
    final notificationService = NotificationService();
    await notificationService.init();

    // 最后再显示窗口
    await windowManager.show();
    await windowManager.focus();

  } catch (e) {
    debugPrint('Initialization error: $e');
  }

  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => AuthProvider()),
        ChangeNotifierProvider(create: (_) => MemberProvider()),
        ChangeNotifierProvider(create: (_) => TaskProvider()),
        ChangeNotifierProvider(create: (_) => MemberFilterProvider()),
        ChangeNotifierProvider.value(value: themeProvider),
      ],
      child: const MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeProvider>(
      builder: (context, themeProvider, child) {
        return MaterialApp(
          title: '俱往矣，数风流人物，还看今朝。',
          theme: themeProvider.getTheme(brightness: Brightness.light),
          darkTheme: themeProvider.getTheme(brightness: Brightness.dark),
          themeMode: themeProvider.themeMode,
          debugShowCheckedModeBanner: false,
          home: FutureBuilder(
            future: Future.wait([
              DatabaseService().database,
              Future.delayed(const Duration(milliseconds: 300)),
            ]),
            builder: (context, snapshot) {
              if (snapshot.hasError) {
                return CustomWindowFrame(
                  child: Scaffold(
                    body: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Text('初始化失败'),
                          const SizedBox(height: 8),
                          Text('错误信息: ${snapshot.error}'),
                          const SizedBox(height: 16),
                          ElevatedButton(
                            onPressed: () {
                              // 重试逻辑
                            },
                            child: const Text('重试'),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              }
              if (!snapshot.hasData) {
                return CustomWindowFrame(
                  child: Scaffold(
                    body: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Text(
                            '黄裳元吉代办',
                            style: TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 16),
                          const CircularProgressIndicator(),
                        ],
                      ),
                    ),
                  ),
                );
              }
              return const WelcomeScreen();
            },
          ),
        );
      },
    );
  }
}

class WelcomeScreen extends StatefulWidget {
  const WelcomeScreen({super.key});

  @override
  State<WelcomeScreen> createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen> {
  late TextEditingController _emailController;
  late TextEditingController _passwordController;
  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    _emailController = TextEditingController();
    _passwordController = TextEditingController();
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  void _showLoginDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text('用户登录'),
        content: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _emailController,
                decoration: const InputDecoration(
                  labelText: '用户名',
                  icon: Icon(Icons.person),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _passwordController,
                decoration: const InputDecoration(
                  labelText: '密码',
                  icon: Icon(Icons.lock),
                ),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              _emailController.clear();
              _passwordController.clear();
              Navigator.pop(context);
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                final memberProvider = Provider.of<MemberProvider>(context, listen: false);
                final authProvider = Provider.of<AuthProvider>(context, listen: false);

                memberProvider.getMemberByName(_emailController.text).then((member) {
                  if (member != null && member.password == _passwordController.text) {
                    authProvider.setCurrentUser(member);
                    _emailController.clear();
                    _passwordController.clear();
                    Navigator.pop(context);  // 关闭登录对话框
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => const HomeScreen()),
                    );
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('欢迎回来，${member.name}')),
                    );
                  } else {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('登录失败：账号或密码错误')),
                    );
                  }
                });
              }
            },
            child: const Text('登录'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CustomWindowFrame(
      title: '欢迎使用',  // 设置窗口标题
      child: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                '欢迎使用\n俱往矣，数风流人物，还看今朝。',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 32,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 16),
              const Text(
                '默认账号：\n'
                '管理员：admin\n'
                '成员：member\n'
                '密码：123456',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey,
                ),
              ),
              const SizedBox(height: 32),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(builder: (context) => const HomeScreen()),
                      );
                    },
                    child: const Text('访客使用'),
                  ),
                  const SizedBox(width: 16),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Theme.of(context).colorScheme.primary,
                      foregroundColor: Colors.white,
                    ),
                    onPressed: () => _showLoginDialog(context),
                    child: const Text('用户登录'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
